package com.jhoncy.myproject.system.service;

import com.github.pagehelper.PageHelper;
import com.jhoncy.myproject.common.dto.PageInfo;
import com.jhoncy.myproject.common.security.oauth.dto.CustomUserDetails;
import com.jhoncy.myproject.system.entity.SysUser;
import com.jhoncy.myproject.system.mapper.SysUserMapper;
import com.jhoncy.myproject.util.MD5Util;
import com.jhoncy.myproject.util.PageUtil;
import com.jhoncy.myproject.util.UUIDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhuangqi
 * @@date 2017/2/23.
 */
@Service
public class SysUserService implements UserDetailsService{

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 所用系统用户
     * @return
     */
    public List<SysUser> listUser(int start, int rows) {
        PageHelper.startPage(start,rows);
        return sysUserMapper.selectAll();
    }

    /**
     * 新增系统用户
     * @param sysUser
     */
    public void saveUser(SysUser sysUser) {
        sysUser.setUserId(UUIDUtil.getUUID());
        sysUser.setPassword(MD5Util.GetMD5Code(sysUser.getPassword()));
        sysUserMapper.insert(sysUser);
    }

    /**
     * 更新用户信息
     * @param userId
     * @param sysUser
     */
    public void updateUser(String userId,SysUser sysUser) {
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        BeanUtils.copyProperties(user,sysUser);
        sysUserMapper.updateByPrimaryKey(user);
    }

    /**
     * 删除用户
     * @param userId
     */
    public void deleUser(String userId) {
        sysUserMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser clientUser = new SysUser();
        clientUser.setUsername(userName);
        SysUser sysUser = sysUserMapper.selectOne(clientUser);
        if( sysUser == null ){
            throw new UsernameNotFoundException(String.format("User with username=%s was not found", userName));
        }
        return new CustomUserDetails(sysUser,true, true, true, true, null);
    }
}
